<?php

namespace App\Http\Controllers;

use App\Order;
use App\User;
use App\Wechat;
use Illuminate\Http\Request;
use EasyWeChat\Factory;

/**
 * Class PayController
 * @package App\Http\Controllers
 */
class PayController extends Controller
{
    //初始化支付信息
    private $app;

    /**
     * 初始化支付信息
     * PayController constructor.
     */
    public function __construct()
    {
        $config = [
            // 必要配置
            'app_id' => env('WECHAT_APPID'),
            'mch_id' => env('WECHAT_MCH_ID'),
            'key' => env('WECHAT_KEY'),   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => public_path('/wechatPem/apiclient_cert.pem'), // XXX: 绝对路径！！！！
            'key_path' => public_path('/wechatPem/apiclient_key.pem'), // XXX: 绝对路径！！！！

            'notify_url' => Wechat::NOTIFY_URL,     // 你也可以在下单时单独设置来想覆盖它
        ];

        $this->app = Factory::payment($config);

    }

    /**
     * 统一下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pay(Request $request)
    {
        //参数校验
        if (!$request->has('order_num')) {
            return response()->json(['code' => 500, 'msg' => '缺少参数']);
        }
        //订单信息
        $order_num = $request->order_num;
        $order = Order::select('uuid', 'price', 'order_num')->where('order_num', $order_num)->first();
        if (!$order) {
            return response()->json(['code' => 500, 'msg' => '订单信息有误']);
        }
        //用户信息
        $open_id = User::where('uuid', $order->uuid)->value('wx_open_id');
        if (!$open_id) {
            return response()->json(['code' => 500, 'msg' => '用户信息有误']);
        }
        //金额
        $num = Order::select('uuid', 'price', 'order_num')->where('order_num', $order_num)->sum('price');
        $price = bcmul($num, 100, 0);
        //生成数据库订单
        $result = Order::UnifiedOrder($this->app, $order->order_num, $price, $open_id);
        return response()->json($result);
    }

    /**
     * @param Request $request
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function checkStatus(Request $request)
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            logger($message);
            return true;
        });
        return $response;
        logger($request->all());
    }


    /**
     * 付款成功
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function paySuccess(Request $request)
    {
        //参数校验
        if (!$request->has('order_num')) {
            return response()->json(['code' => 500, 'msg' => '缺少参数']);
        }
        //订单信息
        $order_num = $request->order_num;
        $order = Order::where('order_num', $order_num)->first();
        if (!$order) {
            return response()->json(['code' => 500, 'msg' => '订单信息有误']);
        }
        //修改订单状态
        $order->type = Order::STATUS_RECEIVING;
        if (!$order->save()) {
            return response()->json(['code' => 500, 'msg' => '订单状态修改失败']);
        }

        return response()->json(['code' => 200, 'msg' => '成功']);
    }

    /**
     * 退款
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function refund(Request $request)
    {
        //订单信息
        $order_num = $request->order_num;
        $order = Order::where('order_num', $order_num)->first();
        if (!$order) {
            return response()->json(['code' => 500, 'msg' => '订单信息有误']);
        }
        $price = bcmul($order->price, 100, 0);
        $result = $this->app->refund->byOutTradeNumber($order_num, $order_num . '1', $price, $price, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '活动结束金额返还',
        ]);
        if ($result['return_code'] !== "SUCCESS" || $result['result_code'] !== "SUCCESS") {
            return response()->json(['code' => 500, 'msg' => '退款失败']);
        }
        return response()->json(['code' => 200, 'msg' => '退款成功']);
    }
}
